<?php

namespace Frieza\Modules\Activity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Activity\DemandHelperFeedback;
use Doraemon\model\Activity\DemandHelperReport;
use Doraemon\model\Comment as dbComment;
use Doraemon\model\CommentActivity as DbCommentActivity;
use Doraemon\pockets\excel\DownExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;


class DemandFeedbackController extends Controller
{
    private $statusMap = [
        DemandHelperFeedback::FEEDBACK_AVE => '一般',
        DemandHelperFeedback::FEEDBACK_SAT => '满意',
        DemandHelperFeedback::FEEDBACK_SUR => '惊喜',
    ];

    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = '需求助手反馈列表';

        $tab->add($title, $this->listData($request));

        return $content
            ->header('需求助手反馈管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }


    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);
        $query = [];

        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query['uid'] = $search['uid'];
        }

        if (!empty($search['unique_code'])) {
            $query['unique_code'] = $search['unique_code'];
        }


        $export = $query;
        $export['page'] = $page;
        $export['page_size'] = $pageSize;
        $export_url = http_build_query($export);

        $feedbackData = $this->getFeedbackData($query, $page, $pageSize);

        $gridModel = new pGridDataModel($feedbackData['data'], $feedbackData['total'], ['perPage' => $pageSize, '']);


        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search, $export_url) {
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->paginate($gridModel->getPerPage());
            $grid->tools(function ($tools) use ($export_url) {
                $tools->append(<<<HTML
<a class="btn button-success" href="/admin/activity/demandFeedback/export?{$export_url}">
    <i class="fa fa-download"/> 导出
</a>
HTML
                );
            });
            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.unique_code', '答题唯一码')->default($search['unique_code']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->column('id');
            $grid->column('uid', '用户id');
            $grid->column('first_time', '解锁时间')->display(function ($first_time) {
                return date("Y-m-d H:i:s", $first_time);
            });
            $grid->column('status', '状态')->using($this->statusMap);
            $grid->column('content', '内容');

            $grid->actions(function ($actions) {
                $actions->disableEdit();
                $actions->disableView();
                $actions->disableDelete();
            });

        });

        return $listGrid->render();

    }

    private function getFeedbackData($query, $page, $pageSize)
    {
        $data = [
            "data" => [],
            "total" => 0
        ];

        $data['total'] =  DemandHelperFeedback::count($query);

        $query['LIMIT'] = [($page-1) * $pageSize, $pageSize];

        $list = DemandHelperFeedback::select('*', $query);

        if ($list && is_array($list)){
            $sort = [];
            foreach ($list as &$val) {
               $val['first_time'] = DemandHelperReport::get("first_get_time", ['uid' => $val['uid'], 'unique_code' => $val['unique_code']]);
               $sort[] = $val['first_time'];
            }
            array_multisort($sort, SORT_DESC, $list);
            $data['data'] = $list;
        }
        return $data;
    }


    public function export(Request $request)
    {
        $query = $request->all();
        $page = $query['page'] ?? 1;
        $pageSize = $query['page_size'] ?? 1;
        unset($query['page']);
        unset($query['page_size']);
        unset($query['_pjax']);

        $list = $this->getFeedbackData($query, $page, $pageSize);
        $exportData = $list['data'];

        if (empty($exportData)) {
            $result = ['status' => 1, 'message' => '暂无数据可以导出'];
            return response()->json($result);
        }

        $downExcel = new DownExcel();
        $title = "需求助手反馈数据";
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $widths = [
            'A' => 10,
            'B' => 15,
            'C' => 15,
            'D' => 20,
            'E' => 50,
        ];
        $downExcel->setWidth($widths);
        $head = [
            'ID',
            'UID',
            '解锁时间',
            '状态',
            '反馈内容',
        ];
        foreach ($exportData as $row) {
            $data[] = [
                $row['id'],
                $row['uid'],
                date('Y-m-d H:i:s', $row['first_time']),
                $this->statusMap[$row['status']] ?? '',
                $row['content'],
            ];
        }

        $downExcel->create($data, $head);
        return back();

    }
}